<template>
  <el-dialog
    v-model="productModifyDialog"
    title="修改业务产品"
    width="500px"
    @close="close"
  >
    <el-form :model="ProductForm">
      <el-form-item label="原产品">
        {{ modProduct.BusinessClassName }} > {{ modProduct.ProductName }}
      </el-form-item>
      <el-form-item label="修改为">
        <el-cascader
          v-model="modProduct.selectProduct"
          :options="productClassOptions"
          :props="SelectProps"
          style="width: 300px"
        />
        <el-button
          type="primary"
          style="margin-left: 20px"
          @click="modProductOK"
        >
          确认修改
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-card shadow="hover">
    <el-descriptions
      class="margin-top"
      title="签约业务产品"
      :column="3"
      :size="size"
      border
    >
      <template #extra>
        <div
          v-if="OrderInfo.BusinessOrderType === 2"
          style="text-align: left; color: #ff0000; padding-right: 30px"
        >
          <span style="color: #999">回签商机上次服务产品：</span>
          {{ OrderInfo.upOrderInfo.ProductName }}（{{
            OrderInfo.upOrderInfo.BindStoreAccount
          }}）
          <span style="color: #999">到期时间：</span>
          {{ OrderInfo.upOrderInfo.ServiceEndDate }}
        </div>
      </template>
    </el-descriptions>
    <div style="padding-bottom: 10px">
      <el-table v-loading="listLoading" :data="ProductList" show-summary>
        <el-table-column
          align="center"
          label="产品ID"
          prop="OrderListID"
          show-overflow-tooltip
          width="60"
        />
        <el-table-column
          align="center"
          label="业务类型"
          prop="BusinessClassName"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          align="center"
          label="产品名称"
          show-overflow-tooltip
          :width="appoint ? '150' : ''"
        >
          <template #default="{ row }">
            <div style="cursor: pointer" @click="productModify(row)">
              {{ row.ProductName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="产品价格"
          prop="ProductPrice"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          align="center"
          label="产品数量"
          prop="ProductNum"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          align="center"
          label="产品签约金额"
          prop="ProductMoney"
          show-overflow-tooltip
          :width="appoint ? '130' : ''"
        />
        <el-table-column
          align="center"
          label="成本金额"
          prop="ProductCost"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="计划服务期限"
          show-overflow-tooltip
          width="200"
        >
          <template #default="{ row }">
            {{ row.PlanServiceStartDate }} 至 {{ row.PlanServiceEndDate }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          :width="appoint ? '220' : '150'"
        >
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-button
                v-if="row.BindStoreID != 0"
                type="success"
                size="small"
                @click="productEdit(row)"
              >
                补充详情
              </el-button>
              <el-button
                v-else
                type="danger"
                size="small"
                @click="productEdit(row)"
              >
                补充详情
              </el-button>
              <el-button
                v-if="OrderFlowState === 1"
                type="danger"
                size="small"
                @click="productDelete(row)"
              >
                删除
              </el-button>
              <el-button
                v-if="appoint"
                :color="row.TaskSetState == 3 ? '#626aef' : ''"
                :type="
                  row.TaskSetState == 0
                    ? `danger`
                    : `${row.TaskSetState == 1 ? `warning` : `${row.TaskSetState == 2 ? `success` : `info`}`}`
                "
                size="small"
                @click="toAudit(row)"
              >
                审核约定任务
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="服务状态"
          show-overflow-tooltip
          width="200"
        >
          <template #default="{ row }">
            <div v-if="row.ServiceState == 0">待提单确认</div>
            <div v-if="row.ServiceState == 2">已提单</div>
            <div v-if="row.ServiceState == 3">已分单待运营</div>
            <div v-if="OrderType === 8 && row.ServiceState == 31">
              换店服务中
            </div>
            <div v-if="OrderType !== 8 && row.ServiceState == 31">
              运营服务中
            </div>
            <div v-if="row.ServiceState == 4">服务暂停中</div>
            <div v-if="row.ServiceState == 5">服务已终止</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="财务状态"
          show-overflow-tooltip
          width="200"
        >
          <template #default="{ row }">
            <div v-if="row.FankState == 1">正常</div>
            <div v-if="row.FankState == 0">已退款</div>
            <div v-if="row.FankState == -1">已退款</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <vab-query-form
      v-if="
        OrderFlowState === 1 ||
        actstaffpostid == 10 ||
        actstaffpostid == 11 ||
        actstaffpostid == 42
      "
      style="padding: 5px"
    >
      <vab-query-form-right-panel :span="24">
        <el-form ref="formRef" :model="ProductForm" :rules="rules">
          <el-space>
            <el-form-item label="选择产品" prop="selectProduct">
              <el-cascader
                v-model="ProductForm.selectProduct"
                :options="productClassOptions"
                :props="SelectProps"
                @change="handleSelectProduct"
              />
            </el-form-item>
            <el-form-item label="数量" prop="ProductNum">
              <el-input-number
                v-model="ProductForm.ProductNum"
                size="small"
                :min="1"
                @change="handleChange"
              />
            </el-form-item>
            <el-form-item label="签约金额" prop="ProductMoney">
              <el-input v-model="ProductForm.ProductMoney" />
            </el-form-item>
            <el-form-item label="成本" prop="ProductCost">
              <el-input v-model="ProductForm.ProductCost" disabled />
            </el-form-item>
            <el-form-item
              label="计划服务期限"
              prop="SeviceDates"
              style="width: 380px"
            >
              <!-- 选择时间组件 -->
              <DateSelect ref="DateSelectRef" @get-date="getDate" />
              <!-- <el-date-picker
                v-model="ProductForm.SeviceDates"
                style="width: 300px"
                type="daterange"
                start-placeholder="服务开始日期"
                end-placeholder="服务结束日期"
              /> -->
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="saveProduct">
                确认添加
              </el-button>
            </el-form-item>
          </el-space>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <trusteeship ref="trusteeshipRef" />
    <domain ref="domainRef" />
  </el-card>
  <!-- 约定任务设置 -->
  <AgreedTaskEdit ref="AgreedTaskEditRef" @fetch-data="Update" />
</template>

<script>
  import DateSelect from '/src/components/DateSelect.vue'
  import { ProductClassSelect } from '@/api/common'
  import AgreedTaskEdit from '@/views/business/components/AgreedTaskEdit'

  import { saveOrderProduct, deleteProduct } from '@/api/businessOrderCreate'
  import Trusteeship from '@/views/business/components/Trusteeship'
  import Domain from '@/views/business/components/Domain'

  export default defineComponent({
    name: 'ProductList',
    components: {
      DateSelect,
      AgreedTaskEdit,
      Trusteeship,
      Domain,
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const { refetchData } = inject('tootMethods')

      const state = reactive({
        actstaffpostid: 0,
        value1: '',
        SelectProps: {
          expandTrigger: 'hover',
        },
        AgreedTaskEditRef: null,
        appoint: false,
        OrderInfo: {},
        OrderID: 0,
        OrderType: 0,
        OrderFlowState: 1,
        disabled: false,
        listLoading: false,
        productClassOptions: [],
        formRef: null,
        editRef: null,
        trusteeshipRef: null,
        domainRef: null,
        hostRef: null,
        DateSelectRef: null,
        ProductList: [],
        ProductForm: {
          OrderListID: 0,
          ProductNum: 1,
        },
        title: '',
        rules: {
          selectProduct: [
            { required: true, trigger: 'change', message: '请选择产品' },
          ],
          ProductNum: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择所签约产品数量',
            },
          ],
          ProductMoney: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入所签约产品金额',
            },
          ],
          SeviceDates: [
            {
              required: true,
              trigger: 'change',
              message: '请务必填写服务期限',
            },
          ],
        },
        productModifyDialog: false,
        modProduct: {},
      })
      const showList = (OrderInfo, list, check) => {
        if (check && check == 'appoint') {
          state.appoint = true
        } else {
          state.appoint = false
        }
        state.OrderInfo = OrderInfo
        state.OrderID = OrderInfo.OrderID
        state.OrderType = OrderInfo.OrderType
        state.OrderFlowState = Math.abs(OrderInfo.OrderFlowState)
        console.log(OrderInfo, ' state.OrderFlowState')
        console.log(list, 'ProductListProductListProductList')
        state.ProductForm.OrderID = OrderInfo.OrderID
        if (OrderInfo.OrderFlowState !== 1) {
          state.disabled = true
        }

        state.ProductList = list
      }

      const productModify = (row) => {
        state.modProduct = Object.assign({}, row)
        state.productModifyDialog = true
      }

      const modProductOK = async () => {
        const { msg } = await saveOrderProduct(state.modProduct)
        $baseMessage(msg, 'success', 'vab-hey-message-success')
        state.modProduct = {}
        state.productModifyDialog = false
        emit('fetch-data')
        refetchData()
      }
      const productEdit = (row) => {
        console.log(row, '123')
        const businessClass = row.BusinessClassID
        switch (businessClass) {
          case 1:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 2:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 3:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 4:
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            break
          case 5:
            // if (row.ProductID == 63) {
            //   state.domainRef.showEdit(row, state.OrderFlowState)
            // } else if (row.ProductID == 64) {
            //   state.hostRef.showEdit(row, state.OrderFlowState)
            // } else {
            //   state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            // }
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
            //if (row.ProductID == 64)
            //  state.editRef.showEdit(row, state.OrderFlowState)
            break
          default:
            // state.giftRef.showEdit(row)
            state.trusteeshipRef.showEdit(row, state.OrderFlowState)
        }
      }

      const handleSelectProduct = () => {
        console.log(
          'ProductForm.selectProduct',
          state.ProductForm.selectProduct[2],
          state.productClassOptions
        )
        state.productClassOptions.forEach((item) => {
          if ('children' in item) {
            item.children.forEach((itm) => {
              if ('children' in itm) {
                itm.children.forEach((i) => {
                  if (i.value === state.ProductForm.selectProduct[2]) {
                    state.ProductForm.ProductPrice = i.price
                    state.ProductForm.ProductMoney = i.price
                    state.ProductForm.ProductCost = i.cost
                    console.log('state.ProductForm', state.ProductForm)
                  }
                })
              }
            })
          }
        })
      }

      const productDelete = (row) => {
        console.log(row)
        if (row.OrderListID) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await deleteProduct({
              OrderListID: row.OrderListID,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }
      }
      const saveProduct = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await saveOrderProduct(state.ProductForm)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            state.ProductForm = {
              OrderListID: 0,
            }
            state.DateSelectRef.empty()
            emit('fetch-data')
          }
        })
      }
      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { ProductClassOptions },
        } = await ProductClassSelect()
        state.productClassOptions = ProductClassOptions
        state.listLoading = false
      }

      const Update = () => {
        emit('fetch-data')
      }

      onMounted(() => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const actstaffpost = JSON.parse(userInfo.StaffPostID)
        state.actstaffpostid = actstaffpost[0][1]
        fetchData()
      })
      const toAudit = (row) => {
        console.log(row, 'rowrow')
        if (row.TaskSetState == 0) {
          ElMessageBox.confirm(
            '还未生成约定任务，是否直接生成？',
            '约定任务审核',
            {
              confirmButtonClass: 'confirmButtonClass',
              customClass: 'custom-message-box',
              confirmButtonText: '直接生成',
              cancelButtonText: '等待生成',
              type: 'warning',
            }
          )
            .then(() => {
              // 直接
              state.AgreedTaskEditRef.showEdit(row, 'direct')
            })
            .catch(() => {})
        } else if (row.TaskSetState == 3) {
          state.AgreedTaskEditRef.showEdit(row, 'direct')
        } else {
          state.AgreedTaskEditRef.showEdit(row, 'appoint')
        }
      }

      const getDate = (data) => {
        state.ProductForm.SeviceDates = data
        console.log(data, '子组件传过来的时间数组')
      }

      return {
        ...toRefs(state),
        toAudit,
        Update,
        getDate,
        showList,
        saveProduct,
        productEdit,
        productModify,
        productDelete,
        handleSelectProduct,
        modProductOK,
      }
    },
  })
</script>
<style>
  .confirmButtonClass {
    margin-right: 10px;
  }

  .custom-message-box .el-message-box__btns {
    display: flex;
    justify-content: flex-start;
    flex-direction: row-reverse;
  }
</style>
